/**
 * 玩家控制系统
 */
import { System, World, Entity } from '../ecs';
import { Transform, Weapon, Renderer, Collider, Bullet } from '../components';
import { Input } from '../../input/Input';
import { ParticleSystem } from './ParticleSystem';

export class PlayerControlSystem implements System {
  priority = 10;
  private particleSystem: ParticleSystem;
  private thrusterTimer = 0;

  constructor() {
    this.particleSystem = new ParticleSystem();
  }

  update(deltaTime: number, world: World): void {
    const input = world.resources.input as Input;
    const players = Array.from(world.entities).filter(entity => 
      entity.hasComponent('player') && entity.hasComponent('transform')
    );

    for (const player of players) {
      this.handlePlayerMovement(player, input, deltaTime, world);
      this.handlePlayerShooting(player, input, world);
      this.handleThrusterEffects(player, input, deltaTime, world);
    }
  }

  private handlePlayerMovement(player: any, input: Input, deltaTime: number, world: World): void {
    const transform = player.getComponent('transform') as Transform;
    if (!transform) return;

    const moveSpeed = 400; // 像素/秒
    const { width, height } = world.resources;

    // 重置速度
    transform.velocityX = 0;
    transform.velocityY = 0;

    // 处理移动输入
    if (input.isKeyPressed('w') || input.isKeyPressed('arrowup')) {
      transform.velocityY = -moveSpeed;
    }
    if (input.isKeyPressed('s') || input.isKeyPressed('arrowdown')) {
      transform.velocityY = moveSpeed;
    }
    if (input.isKeyPressed('a') || input.isKeyPressed('arrowleft')) {
      transform.velocityX = -moveSpeed;
    }
    if (input.isKeyPressed('d') || input.isKeyPressed('arrowright')) {
      transform.velocityX = moveSpeed;
    }

    // 边界检查
    const margin = 20;
    if (transform.x <= margin) transform.velocityX = Math.max(0, transform.velocityX);
    if (transform.x >= width - margin) transform.velocityX = Math.min(0, transform.velocityX);
    if (transform.y <= margin) transform.velocityY = Math.max(0, transform.velocityY);
    if (transform.y >= height - margin) transform.velocityY = Math.min(0, transform.velocityY);
  }

  private handlePlayerShooting(player: any, input: Input, world: World): void {
    const weapon = player.getComponent('weapon') as Weapon;
    const transform = player.getComponent('transform') as Transform;
    
    if (!weapon || !transform) return;

    const currentTime = performance.now() / 1000;
    const canFire = currentTime - weapon.lastFireTime >= weapon.fireRate;

    if ((input.isKeyPressed(' ') || input.isFirePressed()) && canFire) {
      this.fireBullet(transform, weapon, world);
      weapon.lastFireTime = currentTime;
    }
  }

  private handleThrusterEffects(player: any, input: Input, deltaTime: number, world: World): void {
    const transform = player.getComponent('transform') as Transform;
    if (!transform) return;

    // 如果玩家在移动，创建推进器尾焰效果
    const isMoving = input.isKeyPressed('w') || input.isKeyPressed('arrowup') ||
                     input.isKeyPressed('s') || input.isKeyPressed('arrowdown') ||
                     input.isKeyPressed('a') || input.isKeyPressed('arrowleft') ||
                     input.isKeyPressed('d') || input.isKeyPressed('arrowright');

    if (isMoving) {
      this.thrusterTimer += deltaTime;
      if (this.thrusterTimer >= 0.05) { // 每50ms创建一个粒子
        this.particleSystem.createThrusterTrail(world, transform.x, transform.y);
        this.thrusterTimer = 0;
      }
    }
  }

  private fireBullet(transform: Transform, weapon: Weapon, world: World): void {
    const bullet = new Entity()
      .addComponent('transform', {
        x: transform.x,
        y: transform.y - 25,
        rotation: 0,
        velocityX: 0,
        velocityY: -weapon.bulletSpeed
      })
      .addComponent('renderer', {
        color: weapon.bulletColor,
        radius: 3,
        shape: 'circle' as const
      })
      .addComponent('collider', {
        radius: 3,
        isTrigger: true,
        layer: 'playerBullet'
      })
      .addComponent('bullet', {
        damage: weapon.damage,
        owner: 'player' as const,
        lifeTime: 0,
        maxLifeTime: 3
      });

    world.addEntity(bullet);
  }
}